Component Lifecycle Methods
Each component in React has several “lifecycle methods” using which we can run different pieces of code at particular times in the component processing.
If we remember from our previous articles, in every session we are creating a component, calling the component and rendering that component.
We will create one Component Called as Employee Component.
class Employee extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<h2>Welcome to Employee Component...</h2>
</div>
)
}
}
Lets Call this Component and render that to our root container.
Save these changes, navigate to the browser. We call see that our Employee Component is rendered.
Our Employee Component is inserted into the DOM Tree. This Phase is Called as Mounting.
Commonly used lifecycle methods when an instance of a component is being created and inserted into the DOM are:
constructor()
The constructor of a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, we should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.
Typically, in React constructors are only used for two purposes:
• Initializing local state by assigning an object to this.state.
• Binding event handler methods.
Remember that we should not call setState() in the constructor. Constructor is the only place where we should assign this.state directly. In all other methods, we need to use this.setState() instead.
render()
The render() method is the only required method in a class component. Output of a Component is dependent on what we return from this method.
Render method returns one of the following types:
• React elements
• Arrays and fragments.
• Portals
• String and numbers.
• Booleans or null.
We have discussed about how to return React Elements, Fragments and Portals from render method in our previous Videos. The render() function should be pure, meaning that it should not modify component state
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). If we need to load data from a remote endpoint, this is a good place to instantiate the network request. We have discussed about usage of each one of this in our previous articles.
Now lets go to our Employee Component. Lets create a state object in the Constructor and we will add Name property to this object and we will initialize it to empty. Lets go to render method, we will place one input element using which we can Enter Employee Name. Lets call onChange event on this input and we will update the state object when the onChange event is triggered.
Whenever there is a change in the state data or props data or if forceUpdate method is called, then the component gets re-rendered.
The Commonly used methods when a component is being re-rendered are:
• render()
• componentDidUpdate()
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. We can Use this method to operate on the DOM when the component has been updated. We will see an example on using this method in our upcoming articles.
Then comes the next phase unmounting.
When we develop one application, we develop multiple components as part of it. User will be navigating from one component to another component. Just like going from Home to AboutUs and then navigating to Contact Us tabs.
When we go from one Component to the Other Component, the Previous component will be removed from the DOM and the new Component contents will be displayed in the UI.
That is called Unmounting.
When that happens, we want to Perform any necessary cleanup required, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.
Lets understand this with one example. We will use the same component classes we have developed in our last article. They are ChangeDetection Component Class and Reports Component Class.
Now lets call ChangeDetection Component class and render that to our root container.
Now we will place a button the changedetection component class render method. Lets give the text as Load Reports Lets add onClick attribute and lets call a function.
We will implement the LoadReports function and on click of this function, we will render our Reports Component.
Lets save these changes, navigate to the browser.
We can see the contents of ChangeDetection Component are being displayed. Click on the button, we can see the Contents of Reports Component.
When we have moved from ChangeDetection Component to Reports Component, the ChangeDetection Component gets unmounted and Reports Component will be mounted.
In the ChangeDetection Component Class, getEmployeesCount function, lets display an alert message. Save these changes, navigate to the browser.
Open Developer Tools, we can see the log entry in the console for every 5 seconds. Now lets click on Load Reports Button, we moved away from ChangeDetection Component but our setInterval function code will be getting executed continuously. Resulting we get the alertd even after we moved away from that Component. But that should not happen. We have clear the Interval which we have set.
This is where we will make use of componentWillUnmount()
Method. With in this method, we will call clearInterval Javascript function using which we will clear the setInterval .
Lets save these changes, navigate to the browser. Repeat the same Process again but this time we will not see logs after our ChangeDetection Component is Unmounted.
We will use componentWillUnmount method to Perform clean up tasks.
We have discussed about Commonly used Lifecycle methods of Components.
There are some rarely used lifecycle methods. They are
- getDerivedStateFromProps
- shouldComponentUpdate
- getSnapshotBeforeUpdate
We have discussed about shouldComponentUpdate method in our last article and we will discuss few of the remaining in our upcoming articles.
import ReactDOM from "react-dom";
import React, { Component } from "react";
class ChangeDetection extends React.Component {
constructor(props) {
super(props);
this.state = {
employeeCount:0
};
setInterval(this.getEmployeesCount, 5000);
}
componentWillUnmount(){
clearInterval()
}
getEmployeesCount=()=>{
alert('Fetching the Employee Count from the REST API');
fetch("https://localhost:44306/api/Employee")
.then(res => res.json())
.then(
(result) => {
this.setState({
employeeCount: result.length
});
}
);
}
componentDidMount(){
this.getEmployeesCount();
}
showReports=()=>{
ReactDOM.render(<Reports></Reports>,document.getElementById("root"));
}
render() {
return (
<div>
<h2>Welcome to Component Lifecycle Methods Demonstration...</h2>
<p>
<label>Number of Employees are : <b>{this.state.employeeCount}</b></label>
</p>
<button onClick={this.showReports}>Show Reports</button>
</div>
);
}
}
class Reports extends React.Component {
constructor(props) {
super(props);
this.state = {
employees:[]
};
}
componentDidMount=() => {
this.getEmployees();
}
getEmployees() {
fetch("https://localhost:44306/api/Employee")
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result
});
}
);
}
loadEmployees=()=>{
this.getEmployees();
}
render() {
return (
<div>
<h2>Employees Data...</h2>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Location</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
{this.state.employees.map(emp => (
<tr key={emp.Id}>
<td>{emp.Id}</td>
<td>{emp.Name}</td>
<td>{emp.Location}</td>
<td>{emp.Salary}</td>
</tr>
))}
</tbody>
</table>
<p>
<button onClick={this.loadEmployees}>Reload</button>
</p>
</div>
);
}
}
const element=<ChangeDetection></ChangeDetection>
ReactDOM.render(element,document.getElementById("root"));
© 2020 Pragimtech. All Rights Reserved.